package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelCommendQuery;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import static java.awt.SystemColor.info;

/**
 * Created by 13925 on 2018/10/28.
 */
/*
    游记的控制层
 */
@RestController
@RequestMapping("/travels")
public class TravelsController {

    @Autowired
    private ITravelService travelService;

    @Autowired
    private ITravelCommendService travelCommendService;

    @PostMapping
    public JSONResult save(Travel travel, HttpServletRequest request) {
        JSONResult result = new JSONResult();

        try {
            User user = (User) request.getSession().getAttribute("user_in_session");
            travel.setAuthor(user);
            travelService.save(travel);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @GetMapping("/{id}")
    public Travel get(@PathVariable("id") Long id) {
        return travelService.get(id);
    }

    @PutMapping("/{id}")
    public JSONResult update(Travel travel) {
        JSONResult result = new JSONResult();
        try {
            travelService.update(travel);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @GetMapping
    public PageInfo list(TravelQuery qo) {
        //查询公开的游记
        qo.setIsPublic(true);
        //查询已发布的游记
        qo.setState(Travel.STATE_RELEASE);
        //按照发布时间倒叙排序
        qo.setOrderBy("t.releaseTime DESC");
        return travelService.query(qo);
    }

    @GetMapping("/commends")
    public Object getTravelCommend(TravelCommendQuery qo) {
        qo.setOrderBy("tc.schedule DESC");
        PageInfo info  = travelCommendService.queryForApp(qo);
        return info;
    }


}
